import os
import pandas as pd
import pyautogui,pyperclip,time

from lwui.uibase import mkmain, CUIWindow, QThread, pyqtSignal

class PCWx:
    """用于控制PC端微信和企业微信的自动化操作类"""
    
    WECHAT_HOTKEY = ('ctrl', 'alt', 'w')
    WEWORK_HOTKEY = ('shift', 'alt', 's')
    FIND_HOTKEY = ('ctrl', 'f')
    PASTE_HOTKEY = ('ctrl', 'v')
    ENTER_KEY = 'Enter'

    @classmethod
    def toggle_gui(cls, is_wework=False):
        """切换到微信窗口"""
        if is_wework in (True, '1'):
            pyautogui.hotkey(*cls.WEWORK_HOTKEY)
        else:
            pyautogui.hotkey(*cls.WECHAT_HOTKEY)
        time.sleep(1)

    @classmethod
    def find_name(cls, name):
        """
        查找联系人
        Args:
            name: str, 联系人名称
        """
        pyautogui.hotkey(*cls.FIND_HOTKEY)
        time.sleep(0.2)
        pyperclip.copy(name)
        time.sleep(1)
        pyautogui.hotkey(*cls.PASTE_HOTKEY)
        time.sleep(0.2)
        pyautogui.press(cls.ENTER_KEY)
        time.sleep(1.5)

    @classmethod
    def send_message(cls, msg):
        """
        发送消息
        Args:
            msg: str/any, 要发送的消息内容
        """
        pyperclip.copy(str(msg))
        pyautogui.hotkey(*cls.PASTE_HOTKEY)
        pyautogui.press(cls.ENTER_KEY)

    @classmethod
    def send_msg_to(cls, name, msg):
        """
        查找联系人并发送消息
        Args:
            name: str, 联系人名称
            msg: str, 要发送的消息
        """
        cls.find_name(name)
        cls.send_message(msg)
        time.sleep(1)

class BatchSendAsync(QThread):
    def __init__(self, parent, start_num, is_wework, *kw, **kwargs):
        self.parent = parent
        self.start_num = int(start_num)
        self.is_wework = is_wework == '1'
        super().__init__(parent, *kw, **kwargs)

    def run(self):
        p = self.parent
        start_num = self.start_num
        nums = p._num
        PCWx.toggle_gui(self.is_wework)

        if nums:
            for idx, item in enumerate(p.kv_list[start_num:]):
                if not p.run_flag:
                    print("被取消，退出")
                    break
                    
                wxname, text = item
                PCWx.send_msg_to(wxname, text)
                progress = f"发送: {idx+start_num+1}/{nums} {wxname} {text}"
                p.progress_signal.emit(progress, 0)

MyUI=(
    '@E@file', '@B@load@加载(&L)', '@B@check@检查文本', '@B@check_name@检查名单', '@B@batchSend@批量发送(&B)', '@B@stop@停止批量发送(&C)', '@C@iswework@是否企业微信@0', None, 
    '@E@name@一祎小宝贝', '@E@msg@{name},新春快乐！', '@B@send@原始发送(&S)', '@B@dummy@测试发送', 
    '@CMB@itname@----------|abc', '@B@midBatSend@中途批量发送', None,
    '@T@text', None,
    '@B@reset@复位', '@B@dummy_next@模拟遍历', None,
    # "@e@global_status"
)

class MyApp(CUIWindow):
    progress_signal = pyqtSignal(str, int)
    def __init__(self, *argv, **kw):
        super().__init__(*argv, **kw)
        self._count = 0
        self._num = 0
        self.kv_list = []
        self.run_flag = True
        
        # 添加信号处理
        self.progress_signal.connect(self.on_progress)
        self.update_statusbar('初始化')

    def on_progress(self, progress, status):
        if status != 0:
            self.update_statusbar(f'发送失败: {status}')
        else:
            self.update_statusbar(f'进度: {progress}')

    def btnE_reset(self):
        self.set_etext('text', '')

    def btnE_load(self):
        fn = self.get_or_select_file('file', ns='main', ext="excel files(*.xlsx);;All files(*)")
        if os.path.exists(fn):
            self.kv_list = []
            self._df = pd.read_excel(fn)
            self.btnE_check()
            self.update_statusbar(f"0/{self._num}")
        else:
            self._df = []

    def set_status(self, text: str, color: str = "green"):
        if text:
            self.set_etext("global_status", text)
        self.set_ecolor("global_status", self.ecolor_map.get(color, 0))

    def btnE_check(self):
        lines = []
        for idx, l in self._df.iterrows():
            text = l['template'].format(name=l['name'])
            self.kv_list.append([l['wxname'], text])
            lines.append(f"{l['wxname']}---{text}")
            l['text'] = text

        self.set_etext('text', '\n'.join(lines))
        self._num = len(self.kv_list)
        self.update_ecmb_list('itname', self._df['wxname'].to_list())

    def btnE_check_name(self):
        df = self._df
        count = 0
        nums = len(df.index)
        PCWx.toggle_gui(self.get_etext('iswework'))
        if nums:
            for idx, l in self._df.iterrows():
                k = l['wxname']
                print(f"检查 {k}")
                PCWx.find_name(k)

    def btnE_batchSend(self):
        self.run_flag = True
        self.worker = BatchSendAsync(self, 0, self.get_etext('iswework'))
        self.worker.start()

    def btnE_midBatSend(self):
        uie = self.get_elem('itname')
        idx = uie.currentIndex()
        self.run_flag = True
        self.worker = BatchSendAsync(self, idx, self.get_etext('iswework'))
        self.worker.start()

    def btnE_stop(self):
        self.run_flag = False
        self.update_statusbar("用户停止!")

    def btnE_send(self):
        name, msg = self.get_etexts(['name', 'msg'])
        PCWx.toggle_gui(self.get_etext('iswework'))
        PCWx.send_msg_to(name, msg)

    def btnE_dummy(self):
        name, msg = self.get_etexts(['name', 'msg'])
        text = msg.format(name=name)
        self.set_etext('text', text)

if __name__ == '__main__':
    mkmain(MyApp, '微信批量发送程序', MyUI)